package com.moxiao.yfjh.module.activity.service.merchantInfo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.moxiao.yfjh.framework.common.pojo.PageResult;
import com.moxiao.yfjh.module.activity.controller.admin.merchantInfo.vo.MerchantInfoCreateReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.merchantInfo.vo.MerchantInfoExportReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.merchantInfo.vo.MerchantInfoPageReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.merchantInfo.vo.MerchantInfoUpdateReqVO;
import com.moxiao.yfjh.module.activity.convert.merchantInfo.MerchantInfoConvert;
import com.moxiao.yfjh.module.activity.dal.dataobject.merchantInfo.MerchantInfoDO;
import com.moxiao.yfjh.module.activity.dal.mysql.merchantInfo.MerchantInfoMapper;
import com.moxiao.yfjh.module.system.controller.admin.user.vo.user.UserCreateReqVO;
import com.moxiao.yfjh.module.system.controller.admin.user.vo.user.UserUpdateReqVO;
import com.moxiao.yfjh.module.system.service.dept.DeptService;
import com.moxiao.yfjh.module.system.service.permission.PermissionService;
import com.moxiao.yfjh.module.system.service.user.AdminUserService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;

import static com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.moxiao.yfjh.module.activity.enums.ErrorCodeConstants.MERCHANT_INFO_NOT_EXISTS;

/**
 * 相亲商家信息 Service 实现类
 *
 * @author mx
 */
@Service
@Validated
public class MerchantInfoServiceImpl implements MerchantInfoService {

    @Resource
    private MerchantInfoMapper merchantInfoMapper;

    @Resource
    private AdminUserService userService;
    @Resource
    private DeptService deptService;
    @Resource
    private PermissionService permissionService;

    @Override
    public Long createMerchantInfo(MerchantInfoCreateReqVO createReqVO) {
        // 插入
        MerchantInfoDO merchantInfo = MerchantInfoConvert.INSTANCE.convert(createReqVO);
        // 创建商家用户信息
        UserCreateReqVO userCreateReqVO = new UserCreateReqVO();
        userCreateReqVO.setUsername(createReqVO.getName());
        // 随机商家账户
//        userCreateReqVO.setUsername(NoCommonUtil.generateRandomString(4) + NoCommonUtil.getRandom());
        userCreateReqVO.setNickname(createReqVO.getName());
        userCreateReqVO.setRemark("我是商家用户");
        userCreateReqVO.setPassword("123456");
        userCreateReqVO.setSex(1);
        userCreateReqVO.setUserType(2);
        userCreateReqVO.setDeptId(deptService.getDeptOne());
        userCreateReqVO.setAvatar(createReqVO.getMerchantCover());
        Long userId = userService.createUser(userCreateReqVO);
        // 赋予商户权限-默认权限141
        Set<Long> roleIds = new HashSet<>();
        roleIds.add(141L);
        permissionService.assignUserRole(userId, roleIds);
        createReqVO.setUserId(userId);
        merchantInfo.setUserId(userId);
        merchantInfoMapper.insert(merchantInfo);
        // 返回
        return merchantInfo.getId();
    }

    @Override
    public void updateMerchantInfo(MerchantInfoUpdateReqVO updateReqVO) {
        // 校验存在
        validateMerchantInfoExists(updateReqVO.getId());
        // 更新
        MerchantInfoDO updateObj = MerchantInfoConvert.INSTANCE.convert(updateReqVO);
        //TODO 更新用户信息,当前只更新用户头像
        if(updateReqVO.getUserId() != null){
            UserUpdateReqVO updateUse = new UserUpdateReqVO();
            updateUse.setAvatar(updateReqVO.getMerchantCover());
            updateReqVO.setUserId(updateReqVO.getUserId());
            updateUse.setId(updateObj.getUserId());
            userService.updateMerchant(updateUse);
        }
        merchantInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteMerchantInfo(Long id) {
        // 校验存在
        validateMerchantInfoExists(id);
        // 删除
        merchantInfoMapper.deleteById(id);
    }

    private void validateMerchantInfoExists(Long id) {
        if (merchantInfoMapper.selectById(id) == null) {
            throw exception(MERCHANT_INFO_NOT_EXISTS);
        }
    }

    @Override
    public MerchantInfoDO getMerchantInfo(Long id) {
        return merchantInfoMapper.selectById(id);
    }

    @Override
    public List<MerchantInfoDO> getMerchantInfoList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return merchantInfoMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<MerchantInfoDO> getMerchantInfoPage(MerchantInfoPageReqVO pageReqVO) {
        return merchantInfoMapper.selectPage(pageReqVO);
    }

    @Override
    public List<MerchantInfoDO> getMerchantInfoList(MerchantInfoExportReqVO exportReqVO) {
        return merchantInfoMapper.selectList(exportReqVO);
    }

    @Override
    public MerchantInfoDO getMerchantInfoTodayLast(Date todayStart, Date todayEnd) {
        LambdaQueryWrapper<MerchantInfoDO> lqw = Wrappers.lambdaQuery();
        if (Objects.nonNull(todayStart) && Objects.nonNull(todayEnd)) {
            lqw.between(MerchantInfoDO::getCreateTime, todayStart, todayEnd);
        }
        lqw.orderByDesc(MerchantInfoDO::getCreateTime);
        lqw.last("LIMIT " + 1);
        return merchantInfoMapper.selectOne(lqw);
    }

    @Override
    public Integer getMerchantInfoNo(String activeNo) {
        return merchantInfoMapper.getMerchantInfoNo(activeNo);
    }

    @Override
    public MerchantInfoDO getLongin(Long userId) {
        LambdaQueryWrapper<MerchantInfoDO> lqw = Wrappers.lambdaQuery();
        lqw.eq(true, MerchantInfoDO::getUserId, userId);
        lqw.last("LIMIT " + 1);
        return merchantInfoMapper.selectOne(lqw);
    }
}
